package com.xxxx.vao.server.exception;

import com.xxxx.vao.server.result.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author ：xiongl
 * @date ：Created in 2021/4/22 11:46
 * @description：全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(VaoException.class)
    public RespBean handleRRException(VaoException e){
        log.error(e.getMessage(), e);
        return RespBean.error(e.getMessage());
    }

    /**
     * 路径异常
     * @param e
     * @return
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public RespBean handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return RespBean.error(404, "路径不存在，请检查路径是否正确");
    }

    /**
     * 主键重复异常
     * @param e
     * @return
     */
    @ExceptionHandler(DuplicateKeyException.class)
    public RespBean handleDuplicateKeyException(DuplicateKeyException e){
        log.error(e.getMessage(), e);
        return RespBean.error("数据库中已存在该记录");
    }

    /**
     * 其他异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public RespBean handleException(Exception e){
        log.error(e.getMessage(), e);
        return RespBean.error("操作失败，"+e.getMessage());
    }

    /**
     * spring默认上传大小100MB 超出大小捕获异常MaxUploadSizeExceededException
     */
    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public RespBean handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        log.error(e.getMessage(), e);
        return RespBean.error("文件大小超出10MB限制, 请压缩或降低文件质量! ");
    }

    /**
     * 字段过长异常
     * @param e
     * @return
     */
    @ExceptionHandler(DataIntegrityViolationException.class)
    public RespBean handleDataIntegrityViolationException(DataIntegrityViolationException e) {
        log.error(e.getMessage(), e);
        return RespBean.error("字段太长,超出数据库字段的长度");
    }

    /**
     * SQL异常
     * @param e
     * @return
     */
    @ExceptionHandler(SQLException.class)
    public RespBean mySQLException(SQLException e) {
        if (e instanceof SQLIntegrityConstraintViolationException) {
            return RespBean.error("该数据有关数据，操作失败！");
        }
        log.info("该数据有关数据，操作失败！");
        return RespBean.error("数据库异常，操作失败！");
    }
}
